<script setup lang="ts">import { ref, reactive, onMounted } from 'vue';
import axios from '@/utils/axios';
import { useRouter } from 'vue-router';
import { showFailToast, showSuccessToast } from 'vant';
import 'vant/es/toast/style';

// 路由实例，用于页面跳转
const router = useRouter();

// 表单数据接口定义
interface RegisterFormData {
  email: string;
  password: string;
  nickname: string;
  agreeTerms: boolean;
}

// 注册表单响应式数据
const registerForm = reactive<RegisterFormData>({
  email: '',
  password: '',
  nickname: '',
  agreeTerms: false
});

// 控制注册按钮加载状态的响应式变量
const loading = ref(false);

// 页面加载时尝试恢复表单数据
onMounted(() => {
  const savedFormData = sessionStorage.getItem('registerFormData');
  if (savedFormData) {
    try {
      const parsedData = JSON.parse(savedFormData);
      registerForm.email = parsedData.email || '';
      registerForm.password = parsedData.password || '';
      registerForm.nickname = parsedData.nickname || '';
      registerForm.agreeTerms = parsedData.agreeTerms || false;
      // 恢复后清除存储的数据
      sessionStorage.removeItem('registerFormData');
    } catch (e) {
      console.error('Failed to parse saved form data', e);
    }
  }
});

// 监听表单数据变化并保存到 sessionStorage
const saveFormData = () => {
  sessionStorage.setItem('registerFormData', JSON.stringify({...registerForm}));
};

/**
 * 显示服务条款信息
 */
const showTerms = () => {
  // 保存当前表单数据
  saveFormData();
  router.push('/terms?from=register');
};

/**
 * 跳转到登录页面
 */
const goToLogin = () => {
  router.push('/login');
};

/**
 * 处理用户注册逻辑
 * 包含表单校验、发送注册请求、存储token和页面跳转等操作
 */
const handleRegister = async () => {
  if (!registerForm.agreeTerms) {
    showFailToast('请先同意服务条款');
    return;
  }

  try {
    loading.value = true;

    // 移除 agreeTerms 字段，因为后端不需要这个字段
    const { agreeTerms, ...registerData } = registerForm;

    // axios响应拦截器会处理返回结果，这里只需要调用
    await axios.post('/api/users/register', registerData);
    showSuccessToast('注册成功');
    await router.push('/login?registerSuccess=true');
  } catch (error: any) {
    // axios响应拦截器已经处理了错误提示，这里可以添加额外的错误处理逻辑
    // 如果需要针对特定错误做特殊处理，可以根据error.data.code判断
    console.error('注册失败:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="register-container">
    <div class="register-box">
      <!-- Logo 和标题 -->
      <div class="logo-section">
        <img src="@/assets/logo.png" alt="盒游纪"/>
        <div class="title">
          <h2>欢迎注册盒游纪</h2>
          <p>总有一款你热爱的游戏</p>
        </div>
      </div>

      <!-- 注册表单 -->
      <van-form @submit="handleRegister">
        <van-cell-group inset>
          <van-field
              v-model="registerForm.nickname"
              name="nickname"
              placeholder="昵称"
              :rules="[{ required: true, message: '请输入昵称' }]"
          >
            <template #left-icon>
              <van-icon name="user-o" />
            </template>
          </van-field>

          <van-field
              v-model="registerForm.email"
              name="email"
              placeholder="邮箱"
              :rules="[{ required: true, message: '请输入邮箱' }, { pattern: /^[\w.-]+@[\w.-]+\.\w+$/, message: '请输入正确的邮箱格式' }]"
          >
            <template #left-icon>
              <van-icon name="envelop-o" />
            </template>
          </van-field>

          <van-field
              v-model="registerForm.password"
              type="password"
              name="password"
              placeholder="密码"
              :rules="[{ required: true, message: '请输入密码' }, { min: 6, message: '密码长度不能少于6位' }]"
          >
            <template #left-icon>
              <van-icon name="lock" />
            </template>
          </van-field>
        </van-cell-group>

        <!-- 同意服务条款 -->
        <div class="terms">
          <van-checkbox v-model="registerForm.agreeTerms" checked-color="#00bfff">
            注册表示您已同意
            <span class="terms-link" @click="showTerms">《盒游纪服务条款》</span>
          </van-checkbox>
        </div>

        <div style="margin: 16px;">
          <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="loading"
              :disabled="!registerForm.agreeTerms"
          >
            立即注册
          </van-button>
        </div>
      </van-form>

      <div class="login-link">
        已有账号？<span class="login-link-text" @click="goToLogin">立即登录</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.register-box {
  width: 100%;
  max-width: 350px;
  padding: 30px 20px;
  border-radius: 8px;
  background: white;
  z-index: 100;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.logo-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  flex-direction: column;
}

.logo-section img {
  width: 80px;
  height: 80px;
  margin-right: 0;
  margin-bottom: 15px;
}

.logo-section .title {
  text-align: center;
}

.logo-section .title h2 {
  color: #00bfff;
  font-size: 24px;
  margin: 0;
}

.logo-section .title p {
  color: #999;
  font-size: 14px;
  margin: 5px 0 0;
}

.terms {
  font-size: 12px;
  color: #666;
  text-align: center;
  margin: 15px 0;
}

.terms-link {
  color: #00bfff;
  cursor: pointer;
}

.login-link {
  text-align: center;
  font-size: 14px;
  color: #666;
  margin-top: 20px;
}

.login-link-text {
  color: #00bfff;
  cursor: pointer;
}

:deep(.van-button--disabled) {
  opacity: 0.6;
}
</style>
